package org.suburban.servlet;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.xmpp.JID;

import static java.util.logging.Level.FINE;
import static org.suburban.resource.RequestParams.*;

/**
 * Base class for all client servlets
 * @author Alexey Palamarchuk (slonnik@gmail.com)
 *
 */
@SuppressWarnings("serial")
public class ClientServlet extends XMPPServlet{
	
	/** Originator JID*/
	protected JID originator;
	/** Client JID*/
	protected JID client;
	/** schedule human readable name*/
	protected String scheduleName;
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		/** let's trace params output*/
		if(logger.isLoggable(Level.FINE) == true)
		{
			
			logger.log(Level.FINE, "Incoming request parameters are:");
			@SuppressWarnings("unchecked")
			Enumeration<String> names = req.getParameterNames();
			while(names.hasMoreElements())
			{
				String key = names.nextElement();
				logger.log(FINE, "Parameter={0} Value={1}", new String[]{key, req.getParameter(key)});
			}
		}
		
		/**parse request parameters */		
		String value = req.getParameter(ORIGINATOR);
		if(value == null)
		{
			logger.log(Level.WARNING, "'Originator' parameter is missing in client request.");
		}
		originator = new JID(value);
		
		value = req.getParameter(CLIENT);
		if(value == null)
		{
			logger.log(Level.WARNING, "'Client' parameter is missing in client request.");
		}
		client = new JID(value);
		
		value = req.getParameter(SCHEDULE_NAME);
		if(value == null)
		{
			logger.log(Level.WARNING, "'Schedule name' parameter is missing in client request.");
		}
		scheduleName = value;
	}
	
	/**
	 * Send message from 'client' to 'originator'
	 * @param message
	 * @return -true if message was sent successfully, otherwise false
	 */
	protected boolean sendMessage(String message)
	{
		return sendMessage(message, client, originator);
	}
}
